#include "FormatUtil.h"

int FormatUtil::hexToDecimal(const char* szHex, int len)
{
	int result = 0;
	for (int i = 0; i < len; i++)
	{
		result += (int)pow((float)16, (int)len - i - 1) * hexCharValue(szHex[i]);
	}
	return result;
}

int FormatUtil::hexCharValue(char c)
{
	if (c >= '0' && c <= '9')
		return c - '0';
	else if (c >= 'a' && c <= 'f')
		return (c - 'a' + 10);
	else if (c >= 'A' && c <= 'F')
		return (c - 'A' + 10);

	return 0;
}

std::string& FormatUtil::ReplaceAll(std::string& str, const std::string& old_value, const std::string& new_value)
{
	while (true)
	{
		std::string::size_type   pos(0);
		if ((pos = str.find(old_value)) != std::string::npos)
			str.replace(pos, old_value.length(), new_value);
		else
			break;
	}
	return str;
}

std::string& FormatUtil::LeftTrim(std::string &str)
{
	std::string::iterator iter = find_if(str.begin(), str.end(), not1(std::ptr_fun<int, int>(::isspace)));
	str.erase(str.begin(), iter);
	return str;
}

std::string& FormatUtil::RightTrim(std::string &str)
{
	std::string::reverse_iterator rev_iter = find_if(str.rbegin(), str.rend(), not1(std::ptr_fun<int, int>(::isspace)));
	str.erase(rev_iter.base(), str.end());
	return str;
}

std::string& FormatUtil::Trim(std::string &st)
{
	return LeftTrim(RightTrim(st));
}
